package com.draemoncode.weixindb.server;

import com.draemoncode.weixindb.util.JSONUtil;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class CSession {

    private final static Logger log = LoggerFactory.getLogger(CSession.class);

    private static ChannelHandlerContext channelHandlerContext;

    public static void setChannelHandlerContext(ChannelHandlerContext c){
        if(channelHandlerContext != null){
            try {
                channelHandlerContext.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        channelHandlerContext = c;
    }

    public static Boolean isSessionExists(){
        return channelHandlerContext != null;
    }

    public static void send(CMessagePackage cMessagePackage){
        if(channelHandlerContext != null){
            try {
                Map<String, Object> result = new HashMap<>();
                result.put("type", cMessagePackage.getType());
                result.put("syncid", cMessagePackage.getSyncid());
                result.put("create_time", cMessagePackage.getCreate_time());
                result.putAll(cMessagePackage.getMsg());
                channelHandlerContext.write(JSONUtil.toJson(result) + "\r\n");
                channelHandlerContext.flush();
                log.info("服务端发送消息:" + JSONUtil.toJson(result));
            } catch (Exception e) {
                log.error("无法发送消息给机器人:" + cMessagePackage, e);
//                    throw new BusiException(BusiExceptionConstant.CS_UN_CCONNECT, "无法发送消息给机器人");
            }
        }else{
            log.info("机器人客户端未连接");
//            throw new BusiException(BusiExceptionConstant.CS_UN_CCONNECT, "机器人客户端未连接");
        }
    }

}
